/**
 * @author wangj881
 * @date 2025-01-09 16:22
 */
public class L234_3 {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode1 = new ListNode(2, listNode);
        ListNode listNode2 = new ListNode(2, listNode1);
        ListNode listNode3 = new ListNode(1, listNode2);
        boolean palindrome = new Solution().isPalindrome(listNode3);
        System.out.println(palindrome);
    }

    static class Solution {
        public boolean isPalindrome(ListNode head) {

//            找中间节点
            ListNode slow = head;
            ListNode fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }

//            先反转，再遍历比较
            ListNode pre = null;
            ListNode cur = slow;
            while (cur != null) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }

            while (pre != null) {
                if (head.val != pre.val) {
                    return false;
                }
                head = head.next;
                pre = pre.next;
            }
            return true;
        }
    }
}
